﻿$(function () {
    //根据不同客户端，载入不同的lrzJS（前端图像文件压缩）
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    if (IsPC()) {
        console.log("this is pc!");
        oScript.src = "js/icamera/lrz.pc.min.js";
    }
    else {
        console.log("this is mobile!");
        oScript.src = "js/icamera/lrz.mobile.min.js";
    }
    oHead.appendChild(oScript);
});

//注册摄像头，并在指定的video中显示
function registVideo(videoName, canvasName) {
    // Grab elements, create settings, etc.
    var canvas = document.getElementById(canvasName),
				context = canvas.getContext("2d"),
				video = document.getElementById(videoName),
				videoObj = { "video": true },
				errBack = function (error) {
				    console.log("Video capture error: ", error.code);
				};

    // Put video listeners into place
    if (navigator.getUserMedia) { // Standard
        navigator.getUserMedia(videoObj, function (stream) {
            video.src = stream;
            video.play();
        }, errBack);
    } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
        navigator.webkitGetUserMedia(videoObj, function (stream) {
            video.src = window.webkitURL.createObjectURL(stream);
            video.play();
        }, errBack);
    } else if (navigator.mozGetUserMedia) { // WebKit-prefixed
        navigator.mozGetUserMedia(videoObj, function (stream) {
            video.src = window.URL.createObjectURL(stream);
            video.play();
        }, errBack);
    }
}

//判断是否为PC端
function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod", "windows ce", "windows mobile"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}


///////////////
var notesPos = [0, 82, 159, 238, 313, 390, 468, 544];
var timeOut, lastImageData;
var soundContext, bufferLoader;
var notes = [];


function update() {
    //drawVideo();
    blend();
    //checkAreas();
    var timeOut = setTimeout(update, 1000 / 20);
    consloe.log("timeout:" + timeOut);
}

function drawVideo() {
    var canvasSource = $("#canvasSource")[0];
    var contextSource = canvasSource.getContext('2d');
    var video1 = document.getElementById("video1");
    contextSource.drawImage(video1, 0, 0, video1.width, video1.height);
}

function threshold(value) {
    return (value > 0x15) ? 0xFF : 0;
}

function blend() {
    var canvasSource = $("#canvasSource")[0];
    var canvasBlended = $("#canvasBlended")[0];
    var contextSource = canvasSource.getContext('2d');
    var contextBlended = canvasBlended.getContext('2d');
    var video1 = document.getElementById("video1");

    contextSource.drawImage(video1, 0, 0, 640, 480);

    var width = canvasSource.width;
    var height = canvasSource.height;
    // get webcam image data
    var sourceData = contextSource.getImageData(0, 0, width, height);
    // create an image if the previous image doesn’t exist
    if (!lastImageData) lastImageData = contextSource.getImageData(0, 0, width, height);
    // create a ImageData instance to receive the blended result
    var blendedData = contextSource.createImageData(width, height);
    // blend the 2 images
    differenceAccuracy(blendedData.data, sourceData.data, lastImageData.data);
    // draw the result in a canvas

    contextBlended.putImageData(blendedData, 0, 0);
    // store the current webcam image
    lastImageData = sourceData;
}

function differenceAccuracy(target, data1, data2) {
    if (data1.length != data2.length) return null;
    var i = 0;
    while (i < (data1.length * 0.25)) {
        var average1 = (data1[4 * i] + data1[4 * i + 1] + data1[4 * i + 2]) / 3;
        var average2 = (data2[4 * i] + data2[4 * i + 1] + data2[4 * i + 2]) / 3;
        var diff = threshold(fastAbs(average1 - average2));
        target[4 * i] = diff;
        target[4 * i + 1] = diff;
        target[4 * i + 2] = diff;
        target[4 * i + 3] = 0xFF;
        ++i;
    }
}

function fastAbs(value) {
    // equivalent to Math.abs();
    return (value ^ (value >> 31)) - (value >> 31);
}

///////////////

//////////////video3
function recordMove() {
    var width = 640;
    var height = 480;
    var canvasSource = $("#canvasSource")[0];
    var contextSource = canvasSource.getContext('2d');
    var video1 = document.getElementById("video1");

    contextSource.drawImage(video1, 0, 0, width, height);
    width = canvasSource.width;
    height = canvasSource.height;
    var sourceData = contextSource.getImageData(0, 0, width, height);
    if (!lastImageData) lastImageData = contextSource.getImageData(0, 0, width, height);
    
    var imgDiff = imageDifference(sourceData.data, lastImageData.data);
    console.log("imgDiff: " + imgDiff);
    if(imgDiff>10000){
        var imageBase64 = canvasSource.toDataURL('image/jpeg', 50);
        console.log(imageBase64);
        var htmlCode = "<img src=" + imageBase64 + " style='width:320px;'  />";
        $("#td_content").prepend(htmlCode);
    }

    lastImageData = sourceData;
    //
    setTimeout(recordMove, 1000);
}

function imageDifference(data1, data2) {
    if (data1.length != data2.length) return 0;
    console.log(data1.length);
    var i = 0;
    var diffRate = 0;
    while (i < (data1.length * 0.25)) {
        var average1 = (data1[4 * i] + data1[4 * i + 1] + data1[4 * i + 2]) / 3;
        var average2 = (data2[4 * i] + data2[4 * i + 1] + data2[4 * i + 2]) / 3;
        var diff = threshold(fastAbs(average1 - average2));
        if (diff > 0)
        {
            diffRate++;
        }
        ++i;
    }
    return diffRate;
}


/////////////////monitor and view
function recordStorageMove() {
    var width = 640;
    var height = 480;
    var canvasSource = $("#canvasSource")[0];
    var contextSource = canvasSource.getContext('2d');
    var video1 = document.getElementById("video1");

    contextSource.drawImage(video1, 0, 0, width, height);
    width = canvasSource.width;
    height = canvasSource.height;
    var sourceData = contextSource.getImageData(0, 0, width, height);
    if (!lastImageData) lastImageData = contextSource.getImageData(0, 0, width, height);

    var imgDiff = imageDifference(sourceData.data, lastImageData.data);
    //console.log("imgDiff: " + imgDiff);
    if (imgDiff > 10000) {
        var imageBase64 = canvasSource.toDataURL('image/jpeg', 50);
        console.log(imageBase64);
        if (typeof (window.localStorage) != undefined) {
            var storage = window.localStorage;
            storage.setItem('image:' + Math.random(), imageBase64);
        }
    }

    lastImageData = sourceData;
    //
    setTimeout(recordStorageMove, 1000);
}
